/**
 * MIT License
 * 
 * Copyright (c) 2021 CaiDongyu
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package org.axe.spring.cloud.configer;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.axe.util.RequestUtil;
import org.axe.util.ServletDispatcherUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AxeDispatcherFilter implements Filter {
	 private static final Logger LOGGER = LoggerFactory.getLogger(AxeDispatcherFilter.class);

	public static String[] urlMatch;
	public static boolean cross_origin;
	
	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain)
			throws IOException, ServletException {
		do {
			HttpServletRequest request = (HttpServletRequest)arg0;
			if(urlMatch == null) {
					chain.doFilter(arg0, arg1);
					break;
			}
			String path = RequestUtil.getRequestPath(request);
			if(LOGGER.isDebugEnabled()) {
				LOGGER.debug("this path may out of axe:"+path);
			}
			
			boolean matchSuccess = false;//默认未匹配
			for(String pattern:urlMatch) {
				pattern = pattern.trim();
				boolean fullMatch = true;
				if(pattern.endsWith("*")) {
					fullMatch = false;
					pattern = pattern.substring(0,pattern.length()-1);
				}
				if(fullMatch) {
					if(path.equals(pattern)) {
						matchSuccess = true;
						break;
					}
				}else {
					if(path.startsWith(pattern)) {
						matchSuccess = true;
						break;
					}
				}
			}
			if(!matchSuccess) {
				if(LOGGER.isDebugEnabled()) {
					LOGGER.debug("it is real out of axe!");
				}
				chain.doFilter(arg0, arg1);
				break;
			}
			if(LOGGER.isDebugEnabled()) {
				LOGGER.debug("it is match axe success!");
			}
			
			if(cross_origin) {
				HttpServletResponse response = (HttpServletResponse)arg1;
		        /* 允许跨域的主机地址 */
				response.setHeader("Access-Control-Allow-Origin", "*");  
				/* 允许跨域的请求方法GET, POST, HEAD 等 */
				response.setHeader("Access-Control-Allow-Methods", "*");  
				/* 重新预检验跨域的缓存时间 (s) */
				response.setHeader("Access-Control-Max-Age", "3600");  
				/* 允许跨域的请求头 */
				response.setHeader("Access-Control-Allow-Headers", "*");  
				/* 是否携带cookie */
				response.setHeader("Access-Control-Allow-Credentials", "true");
				
				String requestMethod = RequestUtil.getRequestMethod(request);
				if("OPTIONS".equals(requestMethod.toUpperCase())) {
					return;
				}
			}
			
			ServletDispatcherUtil.service(request, (HttpServletResponse)arg1);
		}while(false);
		
	}

}
